import { defineComponent, ref } from "vue";
import { Calendar, DropdownItem } from "vant";
import { DropCalendarItemProps } from "./types";
import moment from "moment";

export default defineComponent({
  name: "",
  props: DropCalendarItemProps,
  emits: ["open", "change"],
  setup(_, { emit }) {
    const show = ref(false);
    const itemRef = ref();
    const onConfirm = (data: any) => {
      const { keys = [] } = _.item!;
      const format = (d: any) => {
        return moment(d).format("YYYY-MM-DD");
      };
      emit("change", {
        [keys[0]]: format(data[0]),
        [keys[1]]: format(data[1]),
      });
      show.value = false;
      itemRef.value.toggle();
    };
    const renderModal = () => {
      return (
        <Calendar
          position="bottom"
          v-model:show={show.value}
          teleport="body"
          type="range"
          confirm-text="完成"
          confirm-disabled-text="请选择结束时间"
          onConfirm={onConfirm}
          defaultDate={_.modelValue
            .filter((e) => e)
            .map((e) => moment(e).toDate())}
        />
      );
    };
    return () => {
      return (
        <DropdownItem
          title={_.item.title}
          onOpened={() => {
            emit("open");
            show.value = true;
          }}
          ref={itemRef}
        >
          {renderModal()}
        </DropdownItem>
      );
    };
  },
});
